package com.wl.application.config;

import com.alibaba.fastjson.JSON;
import com.wl.application.context.LoginLocalThread;
import com.wl.application.common.all.SysLog;
import com.wl.application.common.untils.HttpUtil;
import com.wl.application.entity.SysLoginEntity;
import com.wl.application.mapper.SysLogMapper;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.lang.reflect.Method;
import java.util.Date;

/**
 * @author wl
 * @version 1.0
 * @date 2022/6/27
 * @description: 日志的切面设计
 */
@Component
@Aspect
public class LogAop {
    @Pointcut("@annotation(com.wl.application.common.all.SysLog)")
    public void pointcut(){};

    @Resource
    private SysLogMapper sysLogMapper;

    @Before(value = "pointcut()")
    public void before(){

    }
    @Around("pointcut()")
    public Object around(ProceedingJoinPoint point) throws Throwable {
        //放行
        Object proceed = point.proceed(point.getArgs());
        //环绕后置
        //环绕前置
        //创建日志对象
        SysLoginEntity sysLoginEntity=new SysLoginEntity();
        //1.获取请求的人名
        sysLoginEntity.setUsername(LoginLocalThread.getLocal().getUsername());
        //2.获得请求的地址
        sysLoginEntity.setUrl(HttpUtil.getUrl());
        //3.获得操作时间
        sysLoginEntity.setCreateTime(new Date());
        //4.请求方法的参数
        Object[] args = point.getArgs();
        sysLoginEntity.setParam(JSON.toJSONString(args));
        //5.请求的方法全限定名
        //5.1包名
        String declaringTypeName = point.getSignature().getDeclaringTypeName();
        MethodSignature ms = (MethodSignature) point.getSignature();

        //5.2方法名
        String name = point.getSignature().getName();
        sysLoginEntity.setMethod(declaringTypeName+"."+name);
        //6.操作的名称(注解上value的值)
        Method method = ((MethodSignature) point.getSignature()).getMethod();
        //通过方法来获取
        SysLog annotation = method.getAnnotation(SysLog.class);
        String value = annotation.value();
        sysLoginEntity.setOperate(value);
        //7.存入当前访问的ip
        sysLoginEntity.setIp(HttpUtil.getIp());
        //8.将当前日志信息存在数据库中
        sysLogMapper.insert(sysLoginEntity);

        return proceed;

    }

}
